// pages/index/index.js
// 这里写你的js路径
let QQMapWX = require('./qqmap-wx-jssdk.js');
let qqmapsdk;
let contents = [];
let postTag = 1;
let encounterTag = 1;
let name = "";
const db = wx.cloud.database();
let mapFirstUpdate = true;
let subscriptions = new Set();
const $ = db.command.aggregate;

function getId() {
  var ret = ''
  var ms = (new Date()).getTime()
  ret += base62encode(ms, 8) // 6923年循环一次
  ret += base62encode(Math.ceil(Math.random() * (62 ** 6)), 6) // 冲突概率为每毫秒568亿分之一
  return ret
}
let codeStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

function base62encode(v, n) {
  var ret = ""
  for (var i = 0; i < n; i++) {
    ret = codeStr[v % codeStr.length] + ret
    v = Math.floor(v / codeStr.length)
  }
  return ret
}
Page({
  /**
   * 页面的初始数据
   */
  map: null,
  data: {
    postTagText: "奇遇",
    postImagePath: "",
    location: null,
    postDisplay: 0,
    mapDisplay: 1,
    address: "中国",
    openid: null,
    markers: null,
    encounters: null,
    contentImageDisplay: false,
    contentImage: "",
    content: "",
    contentName: "",
    contentDate: "",
    contentAddress: "中国",
    contentId: "",
    encounterDisplay: 0,
    isLogin: false,
    truedisplay: false,
    opacity: 1,
    opacity1: 0.5,
    zindex: 11,
    zindex1: 10,
    commentsDisplay: 0,
    comments: [],
    commentInput: "dfas",
    canIUseGetUserProfile: true,
    postText: "",
    mineImagePath: "../images/mine.png",
    viewImageDisplay :false,
    viewImagePath:""
  },
  onPostImageClick(){
    this.setData({viewImageDisplay:true,viewImagePath:this.data.postImagePath})
  },
  onImageHideClick(){
    this.setData({viewImageDisplay:false})
  },
  postCommentInput(e) {
    this.setData({
      commentInput: e.detail.value
    })
  },

  onInsertImage() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          postImagePath: res.tempFilePaths
        })
      }
    })
  },

  onPostTag() {
    if (postTag == 1) {
      postTag = 0;
      this.setData({
        postTagText: "邂逅"
      })
    } else {
      postTag = 1;
      this.setData({
        postTagText: "奇遇"
      })
    }
  },

  postComment(e) {
    if(this.data.isLogin){
      wx.showToast({
        title: '请先注册哦！',
        icon: 'error',
        duration: 1500
      })
      return;
    }
    let str = this.data.commentInput.trim();
    if (str == "") {
      wx.showToast({
        title: '内容不能为空哦！',
        icon: 'error',
        duration: 1500
      })
      this.setData({
        commentInput: str
      })
      return;
    }
    wx.showLoading({
      title: '评论中……'
    });
    let that = this;
    wx.cloud.callFunction({
      name: 'addComment',
      data: {
        userName: name,
        id: that.data.contentId,
        content: str
      },
      success(res) {
        //更新评论
        let cs = that.data.comments;
        cs.push({
          content: str,
          userName: name
        });
        that.setData({
          comments: cs,
          commentInput: ""
        })
        //更新其他用户的消息状态
        wx.cloud.callFunction({
          name: 'newSubscription',
          data: {
            encounterId: that.data.contentId,
            userId: that.data.openid,
            isNew: true
          }
        });
        //订阅该事件
        if (subscriptions.has(that.data.contentId))
          return;
        wx.cloud.callFunction({
          name: 'addSubscription',
          data: {
            encounterId: that.data.contentId,
            userId: that.data.openid,
            isNew: false
          }
        });
        //更新状态
        subscriptions.add(that.data.contentId);
      },
      complete() {
        wx.hideLoading()
      }
    })
  },
  getDateString(date) {
    date = new Date(date);
    return date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
  },
  onEncounterClick(e) {
    wx.showLoading({
      title: '加载评论中……'
    });
    let item = e.currentTarget.dataset.index;
    this.setData({
      commentsDisplay: 1,
      content: item.content,
      contentImage: item.imagePath,
      contentImageDisplay: item.imagePath != "",
      contentAddress: item.address,
      contentName: item.name,
      contentDate: item.date,
      contentId: item._id,
      commentInput: ""
    });
    let that = this;
    wx.cloud.callFunction({
      name: 'getComments',
      data: {
        id: this.data.contentId
      },
      success(res) {
        let cs = [];
        for (let i of res.result.data) {
          cs.push(i);
        }
        that.setData({
          comments: cs
        });
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  onMarkerClick(e) {
    let that = this;
    wx.showLoading({
      title: '加载中……'
    });
    wx.cloud.callFunction({
      name: 'getEncounters',
      data: {
        location: contents[e.detail.markerId],
        encounterTag: encounterTag,
        maxDistance: 32
      },
      success(res) {
        let es = [];
        for (let i of res.result.data) {
          i.date = that.getDateString(i.date)
          es.push(i);
        }
        that.setData({
          encounters: es,
          encounterDisplay: true
        });
      },
      complete() {
        wx.hideLoading()
      }
    })
  },


  opentag(e) {
    let index = e.currentTarget.dataset.index
    if (index == 1) {
      encounterTag = 1
      this.setData({
        opacity: 1,
        opacity1: 0.5,
        zindex: 11,
        zindex1: 10
      })
    }
    if (index == 2) {
      encounterTag = 0
      this.setData({
        opacity: 0.5,
        opacity1: 1,
        zindex: 10,
        zindex1: 11
      })
    }
  },
  onCommentsHideClick() {
    this.setData({
      commentsDisplay: 0,
      comments: []
    })
  },

  onClose() {
    this.setData({
      truedisplay: true
    })
  },
  oncloseClick() {
    this.showAll();
    this.setData({
      truedisplay: false
    })
  },

  postInput(e) {
    this.setData({
      postText: e.detail.value
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'CBEBZ-RCTLF-7MXJ6-NOCYU-5RAW5-CEBTK'
    });
    //获取map上下文
    this.map = wx.createMapContext('map');
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '奇遇请求获取您的位置',
            content: '准许咯！',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '啊！？',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '一切就绪！',
                        icon: 'success',
                        duration: 1000
                      })
                    } else {
                      wx.showToast({
                        title: '失败啦！',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  getUserProfile(e) {
    wx.showLoading({
      title: '注册中……',
    })
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        let info = res.userInfo;
        name = info.nickName;
        let that = this;
        wx.cloud.callFunction({
          name: 'addUserInfo',
          data: {
            name: info.nickName,
            gender: info.gender,
            userId: this.data.openid
          },
          success(res) {
            wx.showToast({
              title: '注册好啦！',
              icon: 'success',
              duration: 1500
            })
            that.setData({
              isLogin: false
            });
          }
        })
      },
      fail: (res) => {
        wx.showToast({
          icon: 'none',
          title: '拒绝授权'
        })
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onMapUpdated() {
    if (mapFirstUpdate) {
      this.updateLocation(null);
      mapFirstUpdate = false;
    }
  },

  onReady: function () {
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        this.setData({
          openid: res.result.openid
        })
        //判断用户信息是否存在
        //获取数据库命令对象
        const _ = db.command;
        db.collection("userInfo")
          .where({
            userId: _.eq(this.data.openid)
          })
          .get()
          .then(res => {
            if (res.data.length != 0)
              name = res.data[0].name;
            else
              this.setData({
                isLogin: true
              })
          })
          .then(() => {
            this.initializeSubscriptions();
            this.isNewComments();
          })
          .catch(err => {
            console.error(err)
          })
      }
    });
  },

  isNewComments(){
    this.setData({
      mineImagePath: "../images/mine.png"
    });
    //数据库实例
    const db = wx.cloud.database();
    //获取数据库命令对象
    const _ = db.command;
    db.collection("subscription")
      .where({
        userId: _.eq(this.data.openid),
        isNew: _.eq(true)
      })
      .get()
      .then(res => {
        if (res.data.length > 0) {
          this.setData({
            mineImagePath: "../images/mine_new.png"
          });
        }
      })
      .catch(err => {
        console.error(err)
      })
  },

  initializeSubscriptions() {
    const db = wx.cloud.database();
    //获取数据库命令对象
    const _ = db.command;
    db.collection("subscription")
      .where({
        userId: _.eq(this.data.openid)
      })
      .get()
      .then(res => {
        res.data.forEach((item) => {
          subscriptions.add(item.encounterId);
        })
      })
      .catch(err => {
        console.error(err)
      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.isNewComments();
  },

  onMineClick(e){
    if(this.data.isLogin){
      wx.showToast({
        title: '请先注册哦！',
        icon: 'error',
        duration: 1500
      })
      return;
    }
    wx.navigateTo({
      url: '../mine/mine?userId=' + this.data.openid
    })
  },
  getEncounters(location, isInclude) {
    let that = this;
    wx.cloud.callFunction({
      name: 'getEncounters',
      data: {
        location: location,
        encounterTag: encounterTag,
        maxDistance: 20000
      },
      success(res) {
        let ms = [];
        contents = [];
        res.result.data.forEach((item, i) => {
          contents.push({
            longitude: item.location.coordinates[0],
            latitude: item.location.coordinates[1]
          });
          ms.push({
            latitude: item.location.coordinates[1],
            longitude: item.location.coordinates[0],
            id: i,
            iconPath: item.tag == 1 ? "../images/encounter.png" : "../images/encounter2.png",
            width: 64,
            height: 64,
            anchor: {
              x: 0.5,
              y: 1
            }
          });
        });
        that.setData({
          markers: ms
        })
        if (isInclude) {
          that.map.includePoints({
            points: [...contents, {
                longitude: that.data.location.longitude,
                latitude: that.data.location.latitude
              },
              {
                longitude: that.data.location.longitude + 0.001,
                latitude: that.data.location.latitude
              },
              {
                longitude: that.data.location.longitude - 0.001,
                latitude: that.data.location.latitude
              }
            ],
            padding: [42, 42, 42, 42]
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onAddClick(e) {
    if(this.data.isLogin)
      return;
    this.setData({
      postDisplay: 1
    });
  },

  onHideClick(e) {
    this.setData({
      postDisplay: 0
    });
  },
  onEncounterHideClick() {
    this.setData({
      encounterDisplay: 0
    });
  },
  getFileName(path) {
    path = path.toString();
    return path.substr(path.lastIndexOf('.'));
  },

  onPostClick(e) {
    let eId = getId();
    let postText = this.data.postText.trim();
    this.setData({
      postText: postText
    })
    if (postText == "") {
      wx.showToast({
        title: '内容不能为空哦！',
        icon: 'error',
        duration: 1500
      })
      return;
    }
    this.setData({
      postText: ""
    })
    wx.showLoading({
      title: '发布中……',
    })
    let that = this;
    let imgName = eId + that.getFileName(that.data.postImagePath);
    if (that.data.postImagePath != "") {
      wx.cloud.uploadFile({
        cloudPath: imgName,
        filePath: that.data.postImagePath[0],
        success(res) {
          wx.cloud.callFunction({
            name: 'addEncounter',
            data: {
              imagePath: res.fileID,
              _id: eId,
              postText: postText,
              location: that.data.location,
              openid: that.data.openid,
              tag: postTag,
              address: that.data.address,
              name: name
            },
            success(res) {
              //订阅该事件
              wx.cloud.callFunction({
                name: 'addSubscription',
                data: {
                  encounterId: eId,
                  userId: that.data.openid,
                  isNew: false
                }
              });
              subscriptions.add(eId);
              that.setData({
                postImagePath: ""
              })
              that.getEncounters(that.data.location, false);
              that.onHideClick();
            },
            complete() {
              wx.hideLoading();
            }
          })
        }
      })
    }else{
      wx.cloud.callFunction({
        name: 'addEncounter',
        data: {
          imagePath: "",
          _id: eId,
          postText: postText,
          location: that.data.location,
          openid: that.data.openid,
          tag: postTag,
          address: that.data.address,
          name: name
        },
        success(res) {
          //订阅该事件
          wx.cloud.callFunction({
            name: 'addSubscription',
            data: {
              encounterId: eId,
              userId: that.data.openid,
              isNew: false
            }
          });
          subscriptions.add(eId);
          that.setData({
            postImagePath: ""
          })
          that.getEncounters(that.data.location, false);
          that.onHideClick();
        },
        complete() {
          wx.hideLoading();
        }
      })
    }
  },

  updateLocation(e) {
    //获取位置
    wx.showLoading({
      title: '定位中……',
    })
    wx.getLocation({
      type: "gcj02",
      success: res => {
        this.setData({
          location: res,
        })
        //设置位置
        this.map.moveToLocation();
        this.getLocal(this.data.location.latitude, this.data.location.longitude);
        this.getEncounters(this.data.location, false);
        this.map.includePoints({
          points: [{
              longitude: this.data.location.longitude,
              latitude: this.data.location.latitude
            },
            {
              longitude: this.data.location.longitude + 0.001,
              latitude: this.data.location.latitude
            },
            {
              longitude: this.data.location.longitude - 0.001,
              latitude: this.data.location.latitude
            }
          ],
          padding: [42, 42, 42, 42]
        })
      },
      complete: () => {
        wx.hideLoading();
        this.isNewComments();
      }
    })
  },

  showAll() {
    this.getEncounters(this.data.location, true);
  },

  getLocal: function (latitude, longitude) {
    let page = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        //截取到市
        let str = res.result.address;
        page.setData({
          address: str.length <= 16 ? str : str.substring(str.indexOf("市") + 1)
        });
      }
    });
  }
})